// pages/admin/activity/manage/manage.js
const activityApi = require('../../../../api/activity.js')
const util = require('../../../../utils/util.js')

Page({
  data: {
    activities: [],
    loading: false
  },

  onLoad() {
    this.loadActivities()
  },

  onShow() {
    this.loadActivities()
  },

  async loadActivities() {
    this.setData({ loading: true })

    try {
      const res = await activityApi.getActivityList()
      
      if (res.code === 200) {
        this.setData({
          activities: res.data.items
        })
      }
    } catch (error) {
      console.error('加载活动列表失败:', error)
      util.showError('加载失败')
    } finally {
      this.setData({ loading: false })
    }
  },

  createActivity() {
    wx.navigateTo({
      url: '/pages/admin/activity/edit/edit'
    })
  },

  editActivity(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/admin/activity/edit/edit?id=${id}`
    })
  },

  viewRegistrations(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/admin/registration/list/list?activityId=${id}`
    })
  },

  viewVotes(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/admin/vote/monitor/monitor?activityId=${id}`
    })
  },

  async deleteActivity(e) {
    const id = e.currentTarget.dataset.id

    try {
      await util.confirm('确定要删除这个活动吗？此操作不可恢复', '确认删除')
      
      const res = await activityApi.deleteActivity(id)
      
      if (res.code === 200) {
        util.showSuccess('删除成功')
        this.loadActivities()
      } else {
        util.showError(res.message || '删除失败')
      }
    } catch (error) {
      if (error) {
        console.error('删除活动失败:', error)
        util.showError('删除失败')
      }
    }
  }
})

